package com.febs.web.controller.security;

import com.febs.common.annotation.Limit;
import com.febs.common.domain.FebsConstant;
import com.febs.common.domain.ResponseBo;
import com.febs.security.code.ValidateCode;
import com.febs.security.code.ValidateCodeGenerator;
import com.febs.security.code.sms.SmsCodeSender;

import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * @author zhongyj <1126834403@qq.com><br/>
 * @date 2021/6/18
 */
@Slf4j
@RequiredArgsConstructor
@RestController
public class ValidateCodeController {

    private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();

    private final ValidateCodeGenerator imageCodeGenerator;
    private final ValidateCodeGenerator smsCodeGenerator;
    private final SmsCodeSender smsCodeSender;

    @GetMapping("/images/captcha")
    public void createCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ValidateCode code = imageCodeGenerator.createCode(request, response);
        log.info("登录验证码：【{}】", code);
    }

    @Limit(key = "smscode", period = 60, count = 5, name = "短信验证码", prefix = "limit")
    @GetMapping("/sms/code")
    public ResponseBo createSmsCode(HttpServletRequest request, HttpServletResponse response, String mobile) {
        try {
            ValidateCode smsCode = smsCodeGenerator.createCode(request, response);
            sessionStrategy.setAttribute(new ServletWebRequest(request), FebsConstant.SESSION_KEY_SMS_CODE + mobile, smsCode);
            // 发送短信
            smsCodeSender.send(mobile, smsCode.getCode());
            return ResponseBo.ok();
        } catch (Exception e) {
            log.error("短信验证码发送失败", e);
            return ResponseBo.error();
        }
    }
}
